/*
 * 
 * 
 * 
 */
package com.cms.template.directive;

import com.cms.entity.Content;
import com.cms.entity.Site;
import com.cms.service.ContentService;
import com.cms.utils.FreeMarkerUtils;
import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

/**
 * 模板指令 - 单个内容
 * 
 * 
 * 
 */
@Component
public class ContentDirective extends BaseDirective {

	@Autowired
	private ContentService contentService;
	
	/** "ID"参数名称 */
	private static final String ID_PARAMETER_NAME = "id";

	/** "编码"参数名称 */
	private static final String CODE_PARAMETER_NAME = "code";

	/** 变量名称 */
	private static final String VARIABLE_NAME = "content";

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		Site currentSite = getCurrentSite();
		Integer siteId = currentSite.getId();
		Integer id = FreeMarkerUtils.getParameter(ID_PARAMETER_NAME, Integer.class, params);
		String code = FreeMarkerUtils.getParameter(CODE_PARAMETER_NAME, String.class, params);
		Content content = null;
		if(id==null && StringUtils.isNotBlank(code)){
			content = contentService.findByCode(code,siteId);
		}else{
			content = contentService.getById(id);
		}
		setLocalVariable(VARIABLE_NAME, content, env, body);
	}
}